package work.atpgroup.controller.administrator;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import work.atpgroup.entity.ResourceLink;
import work.atpgroup.entity.User;
import work.atpgroup.entity.WebPage;
import work.atpgroup.entity.tool.ApplicationProperties;
import work.atpgroup.service.PermissionService;
import work.atpgroup.service.ResourceService;
import work.atpgroup.service.WebPageService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Controller
@SessionAttributes(names={"webPage","webPageError"},types = {WebPage.class, String.class})
public class WebPageAdminController {
    @Resource(name="webPageService")
    private WebPageService webPageService;
    @Resource(name="resourceService")
    private ResourceService resourceService;
    @Resource(name="permissionService")
    private PermissionService permissionService;

    @GetMapping("/admin/webPage-list")
    public String adminWebPages(HttpServletRequest request,Model model){
        User user = (User) request.getSession().getAttribute("user");
        ArrayList<WebPage> webPageList = (ArrayList<WebPage>) webPageService.getWebPageByUserId(user.getUserId());
        model.addAttribute("webPageList",webPageList);
        return "admin/webpage";
    }
    @PostMapping("admin/webPage-list/delete/{deleteWebPageId}")
    public void deleteWebPage(@PathVariable String deleteWebPageId, HttpSession session){
        User user = (User) session.getAttribute("user");
        int deletePageId = Integer.parseInt(deleteWebPageId);
        WebPage webPage = webPageService.getWebPageById(deletePageId);
        if(Objects.equals(user.getUserId(), webPage.getUserId())){
            ResourceLink css = resourceService.getResourceLinkById(webPage.getCssId());
            ResourceLink js = resourceService.getResourceLinkById(webPage.getJsId());
            if(css!=null){
                deleteResourceLink(css);
            }
            if(js!=null){
                deleteResourceLink(js);
            }
            webPageService.deleteWebPage(webPage);
        }
    }
    public void deleteResourceLink(ResourceLink resourceLink){
        String path = ApplicationProperties.getAbsoluteLocalPath(resourceLink.getPath());
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }//删除文件
        resourceService.deleteResourceLinkById(resourceLink.getResourceId());//删除数据库中文件引用
    }
    //编辑自己的网页
    @PostMapping("/tryCreateWebPage")
    public String createMyWebPage(@RequestParam("title") String title, @RequestParam("uri") String uri,
                                  @RequestParam("content") String content, HttpServletRequest request,
                                  @RequestParam(value = "css-file",required = false) MultipartFile cssFile, @RequestParam(value = "js-file",required = false) MultipartFile jsFile,Model model)
    {
        WebPage webPage = new WebPage();
        webPage.setContent(content);
        webPage.setTitle(title);
        webPage.setUri(uri);
        if(cssFile!=null){
            System.out.println(cssFile);
            webPage.setCssFile(cssFile);
        }
        if(jsFile!=null){
           webPage.setJsFile(jsFile);
        }
        /*
         * 上面先行执行 数据临时存储，用于恢复网页数据
         * **/
       User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            model.addAttribute("cacheWebPage",webPage);
            model.addAttribute("webPageError","请先进行登录");
            return "public/error/webPageError";
        }
        if(webPageService.getWebPageSizeByUserId(user.getUserId())>=permissionService.getPermissionById(ApplicationProperties.permissionId).getWebPage_limits()){
            model.addAttribute("cacheWebPage",webPage);
            model.addAttribute("webPageError","你已经创建了"+permissionService.getPermissionById(ApplicationProperties.permissionId).getWebPage_limits()+"个网页，为了避免" +
                    "服务器被ddos攻击,以及减少审核的工作量，我们设置了网页创建限制。请尝试删除创建过的网页，然后再次创建网页");
            return "public/error/webPageError";
        }
        if(webPageService.getWebPageByUri(uri)!=null){
            model.addAttribute("cacheWebPage",webPage);
            model.addAttribute("webPageError","该地址已经被占用");
            return "public/error/webPageError";
        }
        if(cssFile.getSize()>1024*1024*5||jsFile.getSize()>1024*1024*5){
            model.addAttribute("cacheWebPage",webPage);
            model.addAttribute("webPageError","上传文件过大，请优化你的css或js文件。限制5mb");
            return "public/error/webPageError";
        }
        assert cssFile != null;// multipartfile 不为空，其返回初始文件名也不为空
        if(Objects.requireNonNull(cssFile.getOriginalFilename()).endsWith(".css")){
            set_css_file(webPage,cssFile,user);
        }
        assert jsFile != null;
        if(Objects.requireNonNull(jsFile.getOriginalFilename()).endsWith(".js")){
            set_js_file(webPage,jsFile,user);
        }
        webPage.setUserId(user.getUserId());
        webPage.setStatus(!permissionService.getPermissionById(ApplicationProperties.permissionId).getWebpagePermission());
        webPageService.insertWebPage(webPage);
        model.addAttribute("successWebPage",webPage);
        model.addAttribute("privateWebPage","webpage/"+webPage.getUri());
        model.addAttribute("publicWebPage","public/"+webPage.getUri());
        return "redirect:webPageSuccess";//redirect:webPageSuccess
    }
    @GetMapping("/webPageSuccess")
    public String webPageSuccess(){
        return "public/success/webPageSuccess";
    }
    public void set_css_file(WebPage webPage,MultipartFile file,User user){
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String newFileName = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));

        ResourceLink resourceLink = new ResourceLink();
        resourceLink.setUserId(user.getUserId());
        resourceLink.setNotThumbnail(true);
        resourceLink.setPath(newFileName);
        resourceLink.setDate(new Date());
        resourceLink.setStatus(!permissionService.getPermissionById(ApplicationProperties.permissionId).getResourcePermission());
        resourceService.insertResourceLink(resourceLink);
        resourceLink.setResourceId(resourceService.getResourceLinkIdByPath(newFileName));

        webPage.setCssId(resourceLink.getResourceId());
        storage(file, newFileName);
    }
    public void set_js_file(WebPage webPage,MultipartFile file,User user){
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String newFileName = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));

        ResourceLink resourceLink = new ResourceLink();
        resourceLink.setUserId(user.getUserId());
        resourceLink.setNotThumbnail(true);
        resourceLink.setPath(newFileName);
        resourceLink.setDate(new Date());
        resourceLink.setStatus(!permissionService.getPermissionById(ApplicationProperties.permissionId).getResourcePermission());
        resourceService.insertResourceLink(resourceLink);
        resourceLink.setResourceId(resourceService.getResourceLinkIdByPath(newFileName));

        webPage.setJsId(resourceLink.getResourceId());
        storage(file, newFileName);
    }

    private void storage(MultipartFile file, String newFileName) {
        String absoluteLocalPath = ApplicationProperties.getAbsoluteLocalPath(newFileName);
        String prePath = absoluteLocalPath.substring(0,absoluteLocalPath.lastIndexOf(File.separator));
        if(!new File(prePath).exists()){
            boolean success = new File(prePath).mkdirs();
            if(!success){
                System.out.println("文件夹不存在，且创建失败！！！！\n");
            }
        }
        try {
            file.transferTo(new File(absoluteLocalPath));
            System.out.println(new File(absoluteLocalPath).exists());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

